package com.tungse.minio.controller;

import com.tungse.minio.cfg.MinioConfig;
import com.tungse.minio.tools.MinioUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

@SpringBootApplication
@RestController
@Slf4j
public class MinioDemoController {

//    @Autowired
//    private MinioClient minioClient;
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private MinioUtils minioUtils;

    /**
     * 要改成使用预签名URL，让前端直接与MinIO交互，减轻服务器负担。
     * 生成上传预签名URL（PUT）
     *
     * @param fileName
     * @return
     */
    @GetMapping("/presigned-upload-url")
    //@ApiOperation("获取上传预签名URL")
    public String generateUploadUrl(@RequestParam("fileName") String fileName) {
        System.out.println("测试" + fileName);
        String url = minioUtils.generatePresignedUploadUrl(minioConfig.getBucketName(), fileName);
        System.out.println("结构" + url);
        return url;
    }

    /**
     * 要改成使用预签名URL，让前端直接与MinIO交互，减轻服务器负担。
     * 生成下载预签名URL（GET）
     *
     * @param fileName
     * @return
     */
    @GetMapping("/presigned-download-url")
    //@ApiOperation("获取下载预签名URL")
    public String generateDownloadUrl(@RequestParam("fileName") String fileName) {
        return minioUtils.generatePresignedDownloadUrl(minioConfig.getBucketName(), fileName);
    }


//    @PostMapping("/upload")
//    public String uploadFile(@RequestParam("file") MultipartFile file) {
//        try {
//            InputStream inputStream = file.getInputStream();
//            ObjectWriteResponse objectWriteResponse =
//                    minioClient.putObject(
//                            PutObjectArgs.builder()
//                                    .bucket(minioConfig.getBucketName())
//                                    .object(file.getOriginalFilename())
//                                    .stream(inputStream, inputStream.available(), -1)
//                                    .contentType(file.getContentType())
//                                    .build()
//                    );
//            return "File uploaded successfully!";
//        } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
//            e.printStackTrace();
//            return "Error uploading file to MinIO: " + e.getMessage();
//        }
//    }


    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            //文件名
            String fileName = file.getOriginalFilename();
            String newFileName = System.currentTimeMillis() + file.getOriginalFilename();// + "." + StringUtils
            // .substringAfterLast(fileName, ".");
            //类型
            String contentType = file.getContentType();
            minioUtils.uploadFile(minioConfig.getBucketName(), file, newFileName, contentType);
            return "上传成功,文件名：" + newFileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

    /**
     * 删除
     *
     * @param fileName
     */
    @DeleteMapping("/")
    public void delete(@RequestParam("fileName") String fileName) {
        minioUtils.removeFile(minioConfig.getBucketName(), fileName);
    }

    /**
     * 获取文件信息
     *
     * @param fileName
     * @return
     */
    @GetMapping("/info")
    public String getFileStatusInfo(@RequestParam("fileName") String fileName) {
        return minioUtils.getFileStatusInfo(minioConfig.getBucketName(), fileName);
    }

    /**
     * 获取文件外链
     *
     * @param fileName
     * @return
     */
    @GetMapping("/url")
    public String getPresignedObjectUrl(@RequestParam("fileName") String fileName) {
        return minioUtils.getPresignedObjectUrl(minioConfig.getBucketName(), fileName);
    }

    /**
     * 文件下载
     *
     * @param fileName
     * @param response
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream fileInputStream = minioUtils.getObject(minioConfig.getBucketName(), fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载失败");
        }
    }

}
